<script setup lang="ts">
  import type { NavItem } from '@nuxt/content/types'
  import type { LocationQueryValue } from 'vue-router'

  import { recipeAPI } from '~/apis/recipe'
  import type { RecipeItem } from '~/apis/recipe/model'

  import { categoryAPI } from '~/apis/category'

  const route = useRoute()
  const recipeStore = useRecipeStore()

  const searchTxt = ref()
  const links = ref<NavItem[]>([])

  const { data: categoryData } = await categoryAPI.search({})

  if (categoryData.value) {
    links.value = [{ id: 0, title: '全部', _path: '' }].concat(
      categoryData.value.map(v => ({ id: v.id, title: v.name, _path: '' }))
    )
  }

  const getLinks = computed(() => {
    const list = links.value.map((v: NavItem) => ({
      ...v,
      id: String(v.id),
      active: String(v.id) === String(state.categories),
      click: () => {
        state.pageNum = 1
        recipeList.value = []
        recipeStore.setCategories(v.id)
        state.categories = v.id
        getList()
      }
    }))
    // .filter((item: NavItem) => {
    //   if (searchTxt.value && searchTxt.value.trim()) {
    //     return item.includes(searchTxt.value)
    //   }
    //   return true
    // })
    return list
  })

  // 菜谱分页
  const pageNum = route.query.page as LocationQueryValue

  if (pageNum && isNaN(Number(pageNum))) {
    throw createError({
      statusCode: 404,
      statusMessage: '未找到菜谱',
      fatal: true
    })
  }

  const state = reactive({
    pageNum: pageNum ? Number(pageNum) : 1,
    pageSize: 9,
    count: 0,
    categories: '0',
    loading: false
  })

  const recipeList = ref<RecipeItem[]>([])

  const getList = async () => {
    try {
      state.loading = true
      const { data: recipeData } = await recipeAPI.page({
        pageNum: state.pageNum,
        pageSize: state.pageSize,
        categories: state.categories
      })
      state.loading = false
      if (!recipeData.value) {
        throw createError({
          statusCode: 404,
          statusMessage: '未找到菜谱列表',
          fatal: true
        })
      }

      if (recipeData.value) {
        // state.count = recipeData.value.count
        // recipeList.value = recipeData.value.list
        state.count = 1
        recipeList.value = [
          {
            id: 11,
            name: '土豆炖牛腩',
            author: 1,
            authorName: '梁傲',
            authorAvatar: 'https://blog-la.oss-cn-hangzhou.aliyuncs.com/blog/assets/avatar.jpeg',
            description: '软烂',
            instructions: [], // 烹饪步骤
            servings: 0,
            coverUrl: 'https://blog-la.oss-cn-hangzhou.aliyuncs.com/blog/assets/avatar.jpeg',
            totalTime: 10,
            difficulty: 'easy', // 菜谱难度
            categories: [], // 分类
            categoriesName: [], // 分类名称
            ingredients: [],
            seasonings: [],
            fruits: [],
            createTime: '2020-10-10'
          }
        ]
      }
    } catch (error) {
      console.error(error)
    }
  }
  getList()

  const updatePageNum = (newPage: number) => {
    state.pageNum = newPage
    recipeList.value = []
    getList()
  }

  const isEmpty = computed(() => {
    return !state.loading && state.count === 0
  })
</script>

<template>
  <UPage>
    <template #left>
      <UAside>
        <template #top>
          <UInput
            v-model:value="searchTxt"
            icon="i-heroicons-magnifying-glass-20-solid"
            size="sm"
            color="white"
            :trailing="false"
            placeholder="搜索分类"
          />
        </template>
        <UNavigationTree :links="mapContentNavigation(getLinks)" />
      </UAside>
    </template>

    <URecipeList :show-empty="isEmpty" :show-loading="state.loading">
      <URecipeItem
        v-for="(recipeItem, index) in recipeList"
        :key="index"
        :to="{ path: `/recipe/detail/${recipeItem.id}` }"
        :title="recipeItem.name"
        :image="
          recipeItem.coverUrl
            ? {
                src: recipeItem.coverUrl,
                loading: 'lazy'
              }
            : undefined
        "
        :date="new Date(recipeItem.createTime ?? '').toLocaleDateString()"
        :authors="[
          {
            name: recipeItem.authorName || '',
            avatar: {
              src: recipeItem.authorAvatar
            },
            to: 'https://gitee.com/lginsane'
          }
        ]"
        :badge="
          recipeItem.categoriesName && !!recipeItem.categoriesName.length
            ? {
                label: recipeItem.categoriesName.join(',') || ''
              }
            : undefined
        "
      ></URecipeItem>
    </URecipeList>

    <UPagination
      v-if="state.count > state.pageSize"
      v-model="state.pageNum"
      :page-count="state.pageSize"
      :total="state.count"
      size="md"
      class="mt-8 flex justify-center"
      @update:model-value="updatePageNum"
    ></UPagination>
  </UPage>
</template>
